package com.sen.paydemo.util;



import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 通过code换取网页授权access_token
 *
 * @作者: 韩宗森
 * @创建时间: 2024/1/11 17:21
 */
public class WeChatUtils {

    private static final String GET_AUTH_CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";

    // 获取code后，请求以下链接获取access_token：
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    // ... 你的appID、secret和重定向uri等变量

    private static final String APP_ID = "wx54572ad02588e188"; // 公众号的唯一标识

    private static final String APP_SECRET = "12f86e37c60c7321f6d4adfe71460910"; // 开发者密钥  公众号的appsecret

    private static final String REDIRECT_URI = "your_redirect_uri"; //


    public static JSONObject getAccessToken(String code) throws Exception {
        // 组装请求URL与参数
        String url = GET_ACCESS_TOKEN_URL + "?appid=" + APP_ID +
                "&secret=" + APP_SECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        // 创建URL对象
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为GET
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 使用Fastjson将JSON字符串转换为JSONObject
            JSONObject jsonObject = JSONObject.parseObject(response.toString());

            return jsonObject;
        } else {
            throw new RuntimeException("请求失败 : HTTP error code : " + responseCode);
        }
    }

}
